﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyBlog.IService;
using MyBlog.Model;
using MyBlog.WebApi.ApiResult;
using System.Threading.Tasks;

namespace MyBlog.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class TypeController : ControllerBase
    {
        private readonly ITypeInfoService _iTypeInfoService;
        public TypeController(ITypeInfoService iTypeInfoService)
        {
            this._iTypeInfoService = iTypeInfoService;  
        }

        [HttpGet("Types")]
        public async Task<ActionResult<ApiResults>> GetTypeInfo()
        {
            var data = await _iTypeInfoService.QueryAsync();
            if (data.Count == 0)
            {
                return ApiResultsHelper.Error(204, "未查询到数据,数据表为空");
            }
            return ApiResultsHelper.Success("查询成功",data);
        }

        [HttpPost("Create")]
        public async Task<ActionResult<ApiResults>> Create(string name)
        {
            TypeInfo type = new TypeInfo() { Name = name };
            var temp = await _iTypeInfoService.FindAsync(c => c.Name == name);
            if (temp != null)
            {
                return ApiResultsHelper.Error(500, "类型已存在");
            }
            bool res = await _iTypeInfoService.CreateAsync(type);
            if (!res)
            {
                return ApiResultsHelper.Error(500,"创建数据失败");
            }
            return ApiResultsHelper.Success(201 ,"创建数据成功");
        }

        [HttpDelete("Delete")]
        public async Task<ActionResult<ApiResults>> Delete(int id)
        {
            bool res = await _iTypeInfoService.DeleteAsync(id);
            if (!res)
            {
                return ApiResultsHelper.Error(500,"删除数据失败");
            }
            return ApiResultsHelper.Success("删除数据成功");
        }

        [HttpPut("Edit")]
        public async Task<ActionResult<ApiResults>> Edit(int id,string name)
        {
            var type = await _iTypeInfoService.FindAsync(id);
            if (type == null)
            {
                return ApiResultsHelper.Error(204,"找不到该类型");
            }
            type.Name = name;
            bool res = await _iTypeInfoService.EditAsync(type);
            if (!res)
            {
                return ApiResultsHelper.Error(500,"修改类型失败");
            }
            return ApiResultsHelper.Success("修改类型成功");
        }
    }
}
